package com.gsmr.util;

import com.gsmr.entity.*;
import com.gsmr.service.AlarmInfoService;
import com.gsmr.service.BS_infoService;
import com.gsmr.service.InterferenceQueryService;
import com.gsmr.service.ServerStateService;
import com.gsmr.service.impl.AlarmInfoServiceImpl;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class AlarmToHistoryTask {
	
	int intervalTime = 0;

	@Resource
	private InterferenceQueryService interferenceQueryService;

	@Resource
	private BS_infoService bsInfoService;

	@Resource
	private AlarmInfoService alarmInfoService;



	final long day = 24 * 3600 * 1000;
	
	/**
	 * 定时任务
	 */
//	@Scheduled(cron = "0 0 0 ? * *") // 间隔1t执行，从凌晨0时0分0秒开始
//	@Scheduled(cron = "0/10 * * * * ?") // 间隔10s执行
//	 @Scheduled(cron = "0 */5 * * * ?")
	public void taskCycle() {
		//insertAlarmInfo(new HashMap<String, Object>());
		 alarmInfoService.testTransactional();
//        updateAlarmHistory();
//		findTRXs();
//		findRxlev();
//		rxlevInfo(7);

    }
  /*
     1.定时扫描alarminfo表中isHandle=1和isNormal=1的告警记录
     2.并插入到alarmHistoryInfo表中
     3.删除alarminfo表中需要清除的数据
   */
//     public void updateAlarmHistory(){
//		Map<String, Object>map = new HashMap<>();
//		map.put("table_name", "alarminfo");
//		map.put("database_name", PropertityUtil.NETWORK_MANAGEMENT_DATABASE_NAME);
//		List<AlarmInfo> list= alarmInfoService.findToAlarmHistoryInfo(map);
//		if (list.size()>0) {
//			System.out.println("开始插入数据到历史告警表！！！");
//			int i = alarmInfoService.insertAlarmHistoryInfo(list);
//			System.out.println("结束插入数据到历史告警表！！！");
//		}
//		long l = System.currentTimeMillis(); //获取时间戳效率最高
//		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
//		String format = dateFormat.format(l);
//		System.out.println("睡眠开始时间==="+format);//2022-09-24
//		try {
//			Thread.sleep(30000);
//		} catch (InterruptedException e) {
//
//			e.printStackTrace();
//
//		}
//		long m = System.currentTimeMillis(); //获取时间戳效率最高
//		String format2 = dateFormat.format(m);
//		System.out.println("睡眠结束时间===="+format2);//2022-09-24
//
//
//		if (list.size()>0) {
//			List<Integer> list_delete= new ArrayList<Integer>();
//			for (AlarmInfo alarminfo:list
//					) {
//				list_delete.add(alarminfo.getAlarmInfoId());
//			}
//			System.out.println("开始删除实时告警表已处理数据！！！");
//			int j = alarmInfoService.deleteAlarmInfo(list_delete);
//			System.out.println("结束删除实时告警表已处理数据！！！");
//		}
//
//	}

	/**
	 * 若TRXs不包含BCCH，插入“外网翻频风险”告警记录
	 */
	void findTRXs() {
		Map<String, Object>map = new HashMap<>();
		List<FScan> scans = findFscan(map);
		for (FScan fScan : scans) {
			if (StringUtil.isEmpty(fScan.getBCCH())) continue;
			String TRXs  = fScan.getTRXs();
			if (StringUtil.isEmpty(TRXs)) continue;
			String[] string = TRXs.split(" ");
			if (string.length < 1) continue;
			
			boolean isContain = false;
			
			for (String str : string) {
				if (StringUtil.isNotEmpty(str) && Integer.valueOf(fScan.getBCCH()).equals(Integer.valueOf(str))) {
					isContain = true;
					break;
				}
			}
			if (isContain) continue;
			
			Map<String, Object>map1 = new HashMap<>();
			map1.put("CID", fScan.getCID());
			map1.put("LAC", fScan.getLAC());
			map1.put("frontProcessorId", fScan.getFrontProcessorId());
			map1.put("alarmTime", fScan.getScanTime());
			map1.put("alarmType", 14);//外网翻频风险
			insertAlarmInfo(map1);
			System.out.println(map1);
		}
	}
	
	/**
	 * 若rxlev大于-20，插入“外网强信号风险”告警记录
	 */
	void findRxlev() {
		Map<String, Object>map = new HashMap<>();
		map.put("rxlev", -20);
		List<FScan> scans = findFscan(map);
		
		for (FScan fScan : scans) {
			Map<String, Object>map1 = new HashMap<>();
			map1.put("CID", fScan.getCID());
			map1.put("LAC", fScan.getLAC());
			map1.put("frontProcessorId", fScan.getFrontProcessorId());
			map1.put("alarmTime", fScan.getScanTime());
			map1.put("alarmType", 13); //外网强信号风险
			insertAlarmInfo(map1);
		}
	}
	
	/**
	 * 查询fscan表的数据
	 */
	private List<FScan> findFscan(Map<String, Object>map) {
		// 1567094400000L
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
		Date lastDate = new Date(now.getTime() - day);
		// map.put("table_name", "gsmr_0513.fscan_" + dateFormat.format(lastDate));
		//map.put("table_name", "gsmr.fscan_" + dateFormat.format(lastDate));
		map.put("table_name", "gsmr.fscan_20190827");
		List<FScan> scans = new ArrayList<>();
		try {
			scans = interferenceQueryService.findFscanCount(map);
		} catch (Exception e) {
			
		}
		return scans;
	}
	
	
	private int[] geitTime(int intervalDat) {
		/*
		 * 20190826	     20190827  	  20190828
		 *    |--------------|------------|
		 * preview	    	last		  now
		 */
		
		Date now = new Date();
		
		long lastTime = now.getTime() - (day * intervalDat);
		long previewTime = now.getTime() - (day * intervalDat * 2);
		
		Date lastDate = new Date(lastTime);
		Date previewDate = new Date(previewTime);
		
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
		
		Integer nowDateInt = Integer.valueOf(dateFormat.format(now));
		Integer lastDateInt = Integer.valueOf(dateFormat.format(lastDate));
		Integer previewDateInt = Integer.valueOf(dateFormat.format(previewDate));
		
		int[] time = {previewDateInt, lastDateInt, nowDateInt};
		return time;
	}
	
	/**
	 * 每间隔一定时间(intervalDat)，从fscan表中查询LAC和CID相同，但RXLEV超过一定值的数据
	 * 例如：查询 fscan_20190828 as t1 和 fscan_20190829 as t2 这两张表的数据
	 * SELECT SUM(RXLEV) as RxlevSum, CID, LAC, COUNT(*) as RxlevCount FROM ${table_name} GROUP BY CID, LAC
	 * 然后比较两张表中LAC和CID相同的数据(t1.LAC == t2.LAC && t1.CID == t2.CID)，但他们的RXLEV的平均值超过10的数据
	 * 产生“外网强信号风险”告警
	 */
	void rxlevInfo(int intervalDat) {
		intervalTime++;
		if (intervalTime % intervalDat != 0) return;
		
		int[] time = geitTime(intervalDat);
		int previewDateInt = time[0];
		int lastDateInt = time[1];
		int nowDateInt = time[2];
		
//		int previewDateInt = 20190826;
//		int lastDateInt = 20190827;
//		int nowDateInt = 20190828;

		// preview至last的结果集
		List<FscanRxlev> previewRxlevs = new ArrayList<>();
		// last至now的结果集
		List<FscanRxlev> lastRxlevs = new ArrayList<>();
		SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		System.out.println("使用SpringMVC框架配置定时任务: " + simpleDateFormat1.format(new Date()));
		
		// 获取两个时间之间的FscanRxlev数据
		setupRxlevsData(previewDateInt, lastDateInt, previewRxlevs);
		setupRxlevsData(lastDateInt, nowDateInt, lastRxlevs);
		
		for (FscanRxlev f1: previewRxlevs) {
			for (FscanRxlev f2 : lastRxlevs) {
				if (f1.getCID() == f2.getCID() && f1.getLAC() == f2.getLAC()) {
					int f1Rxlev = f1.getRxlevSum() / f1.getRxlevCount();
					int f2Rxlev = f2.getRxlevSum() / f2.getRxlevCount();
					if (Math.abs(f1Rxlev - f2Rxlev) > 10) {
						System.out.println("LAC: " + f1.getLAC() + ", CID: " + f1.getCID());
						Map<String, Object>map1 = new HashMap<>();
						map1.put("frontProcessorId",f1.getFrontProcessorId());
						map1.put("alarmTime", f1.getScanTime());
						map1.put("CID", f1.getCID());
						map1.put("LAC", f1.getLAC());
						map1.put("alarmType", 13);//外网强信号风险
						insertAlarmInfo(map1);
					}
					break;
				}
			}
		}
	}
	
	/**
	 * 获取两个时间之间的FscanRxlev数据，当两条数据的LAC和CID相同时，RxlevCount相加，RxlevSum相加
	 * @param from 开始时间
	 * @param to   结束时间
	 * @param des  查询结果
	 */
	private void setupRxlevsData(int from, int to, List<FscanRxlev> des) {
		Map<String, Object>map = new HashMap<>();
		for (int i = from; i < to; i++) {
			try {
				map.put("table_name", "gsmr.fscan_" + i);
		        List<FscanRxlev> findRxlevs = interferenceQueryService.findFscanRxlev(map);
		        if (des.size() < 1) {
		        	des.addAll(findRxlevs);
				} else {
					List<FscanRxlev> tmpRxlev = new ArrayList<>();
	    	        for (FscanRxlev fr1 : findRxlevs) {
						boolean hasSame = false;
						for (FscanRxlev fr2 : des) {
							if (fr1.getCID() == fr2.getCID() && fr1.getLAC() == fr2.getLAC()) {
								fr2.setRxlevCount(fr2.getRxlevCount() + fr1.getRxlevCount());
								fr2.setRxlevSum(fr2.getRxlevSum() + fr1.getRxlevSum());
								hasSame = true;
							}
							if (hasSame) break;
						}
						if (!hasSame) tmpRxlev.add(fr1);
					}
	    	        des.addAll(tmpRxlev);
				}
			} catch (Exception e) {
				//e.printStackTrace();
			}   
		}
	}
	
	/**
	 * 新增一条告警信息
	 */
	private void insertAlarmInfo(Map<String, Object>map) {
		
//		map.put("database_name", PropertityUtil.NETWORK_MANAGEMENT_DATABASE_NAME);
//		map.put("table_name", "history_alarminfo");
//		map.put("alarmType", 13);
//		JSONObject jsonObject = new JSONObject();
//		if (map.containsKey("LAC")) {
//			jsonObject.put("LAC", map.get("LAC"));
//		}
//		if (map.containsKey("CID")) {
//			jsonObject.put("CID", map.get("CID"));
//		}
//		map.put("alarmDetails", jsonObject.toString());
//		
//		map.put("alarmTime", map.getOrDefault("alarmTime", new Date().getTime()));
//		map.put("frontProcessorId", map.getOrDefault("frontProcessorId", 0));
//		
//		map.put("endTime", new Date().getTime());
//		
//		map.put("isHandle", 1);
//		map.put("isNormal", 1);
//		
//		alarmInfoService.insertAlarmInfo(map);
		
		String frontId = map.getOrDefault("frontProcessorId", 0).toString();
		
		String time = map.getOrDefault("alarmTime", new Date().getTime()).toString();
		
		Interference interference = new Interference();
		
		if (frontId.length() > 1) {
			Map<String, Object> map0 = new HashMap<String, Object>();
			map0.put("database_name", PropertityUtil.GSMR_DATABASE);
			map0.put("table_name", "bs_info");
			map0.put("FrontProcessorId", frontId);
			List<BS_info> bsInfoList = bsInfoService.find(map0);
			if (bsInfoList != null && bsInfoList.size() > 0) {
				interference.setBSName(bsInfoList.get(0).getBSName());
			}
		} else {
			interference.setBSName("none");
		}
		interference.setAlarmLevel("5");
		interference.setFrontId(frontId);
		interference.setDirection("1");	
		interference.setEngineID("");
		interference.setKilometer("0");
		interference.setInfIntensity("0");
		interference.setInfBandWidth("200");
		interference.setInfProbability("0");
		interference.setInfChannel("");
		interference.setInfMaxChannel("0");
		interference.setInfSecChannel("0");
		interference.setInfSourceType("移动基站");
		interference.setInfSource("公网运营商干扰");
		interference.setSuspectedInfSource("");
		interference.setDisposed("1");
		interference.setAppear("0");
		interference.setReleaseTime(time);
		interference.setReleaseWay("自动消除");
		interference.setTimeBegin(time);
		interference.setTimeEnd(time);
		String type = map.getOrDefault("alarmType", 0).toString();
		if(type.equals("13")) {
			interference.setTimes("1");
			interference.setInfType("外网强信号风险");
		}
		else {
			interference.setTimes("2");
			interference.setInfType("外网翻频风险");
		}
		interferenceQueryService.insertHistoryInterference(interference);
		
	}
}